﻿namespace GSMock
{
    using System;
    using System.Collections.Specialized;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.XPath;
    using System.Xml.Xsl;

    using GSMock.Extensions;
    using GSMock.Resources;

    /// <summary>
    ///   Builds a response to the search request.
    /// </summary>
    public class ResponseBuilder
    {
        /// <summary>
        ///   Initializes a new instance of the <see cref="ResponseBuilder"/> class.
        /// </summary>
        /// <param name="parameters">The parameters from the request.</param>
        public ResponseBuilder(NameValueCollection parameters)
        {
            this.Parameters = parameters;
        }

        /// <summary>
        ///   Gets the request parameters.
        /// </summary>
        public NameValueCollection Parameters
        {
            get;
            private set;
        }

        /// <summary>
        ///   Returns the response as a string.
        /// </summary>
        /// <returns>
        ///   A string containing the response.
        /// </returns>
        public string GetResponse()
        {
            ResultsManager resultsManager = new ResultsManager();

            string collection = this.Parameters["site"];
            string proxystylesheet = this.Parameters["proxystylesheet"];

            // Get the raw results file.
            XmlDocument results = resultsManager.GetResults(collection);

            // Transform the dynamic parameters.
            ResultsTransformer transformer = new ResultsTransformer(results, this.Parameters);
            results = transformer.Transform();

            if (string.IsNullOrEmpty(proxystylesheet))
            {
                return results.OuterXml;
            }
            else
            {
                return this.TransformResults(results, proxystylesheet);
            }
        }

        /// <summary>
        ///     Transforms a results file through a style sheet.
        /// </summary>
        /// <param name="results">The results file.</param>
        /// <param name="stylesheet">The style sheet file.</param>
        /// <returns>
        ///    The transformed results as a string.
        /// </returns>
        private string TransformResults(XmlDocument results, string stylesheet)
        {
            StylesheetManager stylesheetManager = new StylesheetManager();

            XslCompiledTransform transform = stylesheetManager.GetStylesheet(stylesheet);

            StringBuilder sb = new StringBuilder();
            TextWriter tw = new StringWriter(sb);
            XmlTextWriter xtw = new XmlTextWriter(tw);

            transform.Transform(results, null, xtw);

            return sb.ToString();
        }
    }
}
